package com.product.android.ui.widget;

import android.content.Context;
import android.text.Html;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.method.Touch;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.TextView;

import com.product.android.utils.ContentUtils;
import com.product.android.utils.ContentUtils.URLImageClickSpan;
import com.product.android.utils.ContentUtils.URLSpanNoUnderline;
import com.product.android.utils.ContentUtils.UrlImageSpan;

/**
 * 
 * ClassName:ProTextView Function: 处理@，url ,表情等复杂文本的TextView Reason: TODO ADD REASON
 * 
 * @author huangszh
 * @version
 * @since Ver 1.1
 * @Date 2013 2013-12-11 上午11:38:18
 * 
 * @see
 */
public class ProTextView extends TextView {
    boolean dontConsumeNonUrlClicks = true;
    boolean linkHit = false;

    public ProTextView(Context context) {
        super(context);
    }

    public ProTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ProTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        linkHit = false;
        // reason : the Layout that is currently being used to display the text. This can be null if
        // the text or width has recently changes.
        // result : 导致LinkMovementMethod里面只接收到DOWN的事件，其他再也接收不到，需要特殊处理
        if (getLayout() == null && getText() instanceof Spannable) {
            LocalLinkMovementMethod.getInstance().cleanSelectSpan(this, (Spannable) getText(),
                    event.getAction() == MotionEvent.ACTION_UP);
            linkHit = true;
        }

        boolean res = super.onTouchEvent(event);

        if (dontConsumeNonUrlClicks) {
            res = linkHit;// linkHit在LocalLinkMovementMethod方法中可能改变
        }
        return res;
    }

    @Override
    public boolean performLongClick() {
        return true;
    }

    public void setTextViewHTML(String html) {
        CharSequence sequence = Html.fromHtml(html);
        SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
        setText(strBuilder);
    }

    public static class LocalLinkMovementMethod extends LinkMovementMethod {
        static LocalLinkMovementMethod sInstance;
        private UrlImageSpan mSelectImageSpan;
        private URLSpanNoUnderline mSelectClickSpan;

        public static LocalLinkMovementMethod getInstance() {
            if (sInstance == null)
                sInstance = new LocalLinkMovementMethod();

            return sInstance;
        }

        /**
         * 
         * @n<b>函数名称</b> :cleanSelectSpan
         * @brief 清空之前选中的ClickableSpan和UrlImageSpan，清空之前是否执行ClickableSpan的click事件由外部传参决定
         * @see
         * @since Ver 1.1
         * @param @param widget
         * @param @param buffer
         * @param @param doClick true的话表示清空之前需要执行ClickableSpan的click事件，否则不需要
         * @return void
         * @<b>作者</b> : huangszh
         * @<b>创建时间</b> : 2013-12-19上午9:51:05
         */
        public void cleanSelectSpan(TextView widget, Spannable buffer, boolean doClick) {
            if (mSelectImageSpan != null) {
                ContentUtils.setUrlImageSpan(widget, mSelectImageSpan, buffer, false, null);
                mSelectImageSpan = null;
            }
            if (doClick && mSelectClickSpan != null) {
                mSelectClickSpan.onClick(widget);
            }
            mSelectClickSpan = null;
        }

        @Override
        public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
            try {
                int action = event.getAction();

                if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_MOVE) {
                    int x = (int) event.getX();
                    int y = (int) event.getY();

                    x -= widget.getTotalPaddingLeft();
                    y -= widget.getTotalPaddingTop();

                    x += widget.getScrollX();
                    y += widget.getScrollY();

                    Layout layout = widget.getLayout();
                    int line = layout.getLineForVertical(y);
                    int off = layout.getOffsetForHorizontal(line, x);

                    // 处理@ ，url 等
                    URLSpanNoUnderline[] link = buffer.getSpans(off, off, URLSpanNoUnderline.class);

                    if (action == MotionEvent.ACTION_DOWN) {
                        if (link.length != 0) {
                            // 有Click,判断是否为超链接URL
                            UrlImageSpan[] image = buffer.getSpans(off, off, UrlImageSpan.class);

                            // 是的话,重绘按下状态的URL图片
                            if (image.length != 0) {
                                mSelectImageSpan = ContentUtils.setUrlImageSpan(widget, image[0],
                                        buffer, true, null);
                             // 寻找对应的点击事件
								for(URLSpanNoUnderline temp : link){
									if(temp instanceof URLImageClickSpan){
										// 设置当前选中
										mSelectClickSpan = temp;
										break;
									}
								}
							} else{
								// 设置当前选中
								mSelectClickSpan = link[0];
							}

                            if (widget instanceof ProTextView) {
                                ((ProTextView) widget).linkHit = true;
                            }
                            return true;
                        }
                    } else if (action == MotionEvent.ACTION_MOVE) {
                    	UrlImageSpan[] image = buffer.getSpans(off, off,UrlImageSpan.class);
						// 之前有选中的
						if(mSelectImageSpan != null){
							// 现在没有或者新选中其他
							if(image.length == 0 
									|| !mSelectImageSpan.getUrl().equals(image[0].getUrl())){
								// 那么需要清掉旧的
								cleanSelectSpan(widget, buffer, false);
							}
							
						}
						
						if(image.length != 0){
							// 设置新的选中
							mSelectImageSpan = ContentUtils.setUrlImageSpan(widget, image[0], buffer, true, null);
							// 寻找对应的点击事件
							for(URLSpanNoUnderline temp : link){
								if(temp instanceof URLImageClickSpan){
									// 设置当前选中
									mSelectClickSpan = temp;
									break;
								}
							}
						} else{
							// 设置当前点击事件
							if(link.length != 0){
								mSelectClickSpan = link[0];
							} else {
								mSelectClickSpan = null;
							}
						}
                        if (widget instanceof ProTextView) {
                            ((ProTextView) widget).linkHit = true;
                        }
                        return true;
                    }
                } else if (action == MotionEvent.ACTION_UP) {
                		 // 执行UP
                        cleanSelectSpan(widget, buffer, true);

                        if (widget instanceof ProTextView) {
                            ((ProTextView) widget).linkHit = true;
                        }
                        return true;
                   
                } else {
                    // 接收其它事件(Cancel)的时候状态还原，选中置空，执行父级操作。
                    cleanSelectSpan(widget, buffer, false);
                }

                return Touch.onTouchEvent(widget, buffer, event);
            } catch (NullPointerException e) { // 捕获TextView.getTotalPaddingTop可能存在的NullPointerException
                return false;
            }

        }

    }

}
